package com.yc.ATM;

import com.google.gson.Gson;

import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class BankTask implements Runnable{
    private Socket socket;
    private Bank b;
    private boolean flag;

    public BankTask(Socket s,Bank b){
        this.socket=s;
        this.b=b;
        this.flag=true;
    }

    @Override
    public void run(){
        try(
                //因为要用到tr..response直线关闭socket，所以要将socket重新再try声明
                Socket s=this.socket;
                Scanner reader=new Scanner( s.getInputStream() );
                PrintWriter pw=new PrintWriter(s.getOutputStream());
        ){
            while (flag && !Thread.currentThread().isInterrupted() ){
            //客户端是否没有传数据 如果没有传 则结束
            if (!reader.hasNext()) {
                System.out.println("atm客户端:" + s.getRemoteSocketAddress() + "掉线了");
                break;
            }
            //如果有信息 则取出
            String command = reader.next();//next() 读第一个部分 而没有读取一行
            BankAccount ba = null;

            JsonModel<BankAccount> jm = new JsonModel<BankAccount>();
            //命令模式

            if ("DEPOSIT".equals(command)) {
                int id = reader.nextInt();
                double money = reader.nextDouble();
                ba = b.deposite(id, money);
            } else if ("WITHDRAW".equals(command)) {
                int id = reader.nextInt();
                double money = reader.nextDouble();
                ba = b.withdraw(id, money);
            } else if ("BALANCE".equals(command)) {
                int id = reader.nextInt();
                ba = b.search(id);
            } else if ("QUIT".equals(command)) {
                System.out.println("atm客户端要求主动断开..." + s.getRemoteSocketAddress());
                break;
            } else {
                //pw.println("错误指令");
                jm.setCode(0);
                jm.setErrorMsg("错误命令");

                Gson g = new Gson();
                String jsonString = g.toJson(jm);
                pw.println(jsonString);
                pw.flush();
                continue;
            }

            //TODO : 将基本字符串改为json，这样数据丰富
            //pw.pribtln(ba.getId()+" "+ba.getBalance());

            jm.setCode(1);
            jm.setObj(ba);

            Gson g = new Gson();
            String jsonString = g.toJson(jm);
            pw.println(jsonString);
            pw.flush();
        }

        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
